<template>
  <div class="detail-wrapper customer-detail-wrapper">
    <PageTitle title="返回客户列表" />

    <div
      class="detail-content"
      v-if="Object.keys(detail).length">
      <el-scrollbar>
        <div class="detail-box">
          <div class="detail-title-box">
            <span>基本信息</span>
          </div>

          <div class="detail-info base-info">
            <div class="info-box">
              <div class="item">
                <p>客户账号</p>
                <p>{{ detail.member.accountName }}</p>
              </div>
              <div class="item">
                <p>客户名称</p>
                <p>{{ detail.member.nickName }}</p>
              </div>
              <div class="item">
                <p>联系方式</p>
                <p>{{ detail.member.mobile ? detail.member.mobile : '暂无'  }}</p>
              </div>
              <div class="item">
                <p>实名状态</p>
                <p>{{ detail.member.realInfo }}</p>
              </div>
            </div>
          </div>
          
        </div>

        <div class="detail-box">
          <div class="detail-title-box">
            <span>财务信息</span>
          </div>

          <div class="detail-info base-info">
            <div class="info-box">
              <div class="item">
                <p>客户算力券余额 </p>
                <div class="item-content">
                  <span>{{ detail.member.voucherMoney || 0}} &nbsp;</span>
                  <div class="flex-center">
                    <div>
                      <el-popover
                        placement="bottom"
                        :width="330"
                        trigger="click"
                        popper-class="popover-wrapper"
                        ref="popoverTransfer"
                        @hide="
                          formTransfer.remark = '';
                          formTransfer.rechargeMoney = '';
                          formTransfer.voucherMoney = '';
                          formTransfer.smsCode = '';
                          userStore.getUser();
                        ">
                        <template #reference>
                          <el-text
                            type="primary"
                            class="text-btn">
                            资金划拨 &nbsp;
                          </el-text>
                        </template>
                        <div class="popover-content">
                          <!-- 资金划拨 -->
                          <p class="title">资金划拨</p>
                          <el-form
                            label-position="top"
                            :rules="rules"
                            :model="formTransfer">
                            <el-form-item label="客户本次充值(元)" prop="rechargeMoney">
                              <div class="content-item">
                                <div class="content-item-box">
                                  <el-input
                                    input-style="width:275px;"
                                    v-model="formTransfer.rechargeMoney"
                                    placeholder="请输入" @input="voucherMoneyTemp"/>
                                </div>
                              </div>
                            </el-form-item>
                            <div class="paramsInfo">
                              <div class="item">
                                <div class="title">
                                  客户折扣
                                </div>
                                <div class="value">
                                  {{formTransfer.voucherMoney?parseFloat(formTransfer.rechargeMoney/formTransfer.voucherMoney).toFixed(2): detail.member.discountRatio}}
                                </div>
                              </div>
                              <div class="item">
                                <div class="title">
                                  本次划拨算力券
                                </div>
                                <div class="value">
                                  {{ parseFloat(formTransfer.rechargeMoney /detail.member.discountRatio).toFixed(2) }}
                                </div>
                              </div>
                              <div class="item">
                                <div class="title">
                                  本次收益(元)
                                </div>
                                <div class="value">
                                  {{
                                    formTransfer.voucherMoney && formTransfer.rechargeMoney?
                                   (parseFloat((parseFloat(formTransfer.rechargeMoney/formTransfer.voucherMoney).toFixed(2) - partnerParams1.partnerDiscountRatio).toFixed(2)) * formTransfer.voucherMoney).toFixed(2):
                                   '0.00'
                                  }}
                                </div>
                              </div>
                            </div>

                            <el-form-item label="本次实际划拨" prop="voucherMoney">
                              <div class="content-item">
                                <div class="content-item-box">
                                  <div class="uservoucher">余额：{{ userStore.user.voucher }}</div>
                                  <el-input
                                    input-style="width:275px;"
                                    v-model="formTransfer.voucherMoney"
                                    placeholder="请输入" />
                                </div>
                              </div>
                            </el-form-item>
                            <el-form-item :label="codeLabel" prop="smsCode">
                              <div class="content-item">
                                <div class="content-item-box">
                                  <el-input
                                    v-model="formTransfer.smsCode"
                                    placeholder="请输入" />
                                  <GetMsgCode />
                                </div>
                              </div>
                            </el-form-item>
                            <el-form-item label="备注" prop="remark">
                              <div class="content-item">
                                <div class="content-item-box">
                                  <el-input
                                    v-model="formTransfer.remark"
                                    style="width: 290px;height:50px;"
                                    maxlength="20"
                                    placeholder="请输入"
                                    show-word-limit
                                    type="text"
                                  />
                                </div>
                              </div>
                            </el-form-item>
                          </el-form>

                          <div class="btn-box">
                            <el-button
                              type="primary"
                              @click="confirmTransfer">
                              确认划拨
                            </el-button>
                            <el-button @click="cancelTransfer">取消</el-button>
                          </div>
                        </div>
                      </el-popover>
                    </div>
                    
                    <div>
                      <el-popover
                        placement="bottom"
                        :width="330"
                        trigger="click"
                        popper-class="popover-wrapper"
                        ref="popoverSend"
                        @hide="
                          formSend.voucherMoney = '';
                          formSend.addReason = '';
                          formSend.smsCode = '';
                          userStore.getUser();
                        ">
                        <template #reference>
                          <el-text
                            type="primary"
                            class="text-btn">
                            赠送
                          </el-text>
                        </template>
                        <div class="popover-content">
                          <p class="title">赠送</p>
                          <el-form
                            :rules="rules"
                            label-position="top"
                            :model="formSend">
                            <el-form-item label="本次赠送算力券金额为" prop="voucherMoney">
                              <div class="content-item">
                                <div class="content-item-box">
                                  <el-input
                                    input-style="width:275px;"
                                    v-model="formSend.voucherMoney"
                                    placeholder="请输入" />
                                </div>
                              </div>
                            </el-form-item>
                            <el-form-item label="赠送原因" prop="addReason">
                              <div class="content-item">
                                <div class="content-item-box">
                                  <div class="uservoucher">余额：{{ userStore.user.voucher }}</div>
                                  <el-input
                                    input-style="width:275px;"
                                    v-model="formSend.addReason"
                                    placeholder="请输入" />
                                </div>
                              </div>
                            </el-form-item>
                            <el-form-item :label="codeLabel" prop="smsCode">
                              <div class="content-item">
                                <div class="content-item-box">
                                  <el-input
                                    v-model="formSend.smsCode"
                                    placeholder="请输入" />
                                  <GetMsgCode />
                                </div>
                              </div>
                            </el-form-item>
                          </el-form>

                          <div class="btn-box">
                            <el-button
                              type="primary"
                              @click="confirmSend">
                              确认赠送
                            </el-button>
                            <el-button @click="cancelSend">取消</el-button>
                          </div>
                        </div>
                      </el-popover>
                    </div>
                  </div>
                </div>
              </div>
              <div class="item">
                <p>客户折扣</p>
                <div>
                  <span>{{ detail.member.discountRatio }}</span>
                  <el-popover
                    placement="bottom"
                    :width="330"
                    trigger="click"
                    popper-class="popover-wrapper"
                    ref="popoverDiscount"
                    @hide="
                      formDiscount.discountRatio = '';
                      formDiscount.smsCode = '';
            
                      showDiscountHint = false;
                    ">
                    <template #reference>
                      <el-text
                        type="primary"
                        class="text-btn">
                        &nbsp;
                        折扣
                      </el-text>
                    </template>
                    <div class="popover-content">
                      <div class="title">
                        <p v-if="userStore.user.type !== 3">您当前的折扣为：{{ userStore.user.discountRatio }}</p>
                        <p>客户当前的折扣为：{{ detail.member.discountRatio }}</p>
                      </div>

                      <el-form
                        label-position="top"
                        :model="formDiscount">
                        <el-form-item label="本次调整为">
                          <div class="content-item">
                            <div class="content-item-box">
                              <el-input
                                v-model="formDiscount.discountRatio"
                                placeholder="请输入"
                                @input="checkDiscount" />
                            </div>
                            <p
                              class="hint-text color-danger"
                              v-show="showDiscountHint">
                              调整折扣低于您当前拥有的折扣，会导致亏损，请仔细核对后调整。
                            </p>
                          </div>
                        </el-form-item>
                        <el-form-item :label="codeLabel">
                          <div class="content-item">
                            <div class="content-item-box">
                              <el-input
                                v-model="formDiscount.smsCode"
                                placeholder="请输入" />
                              <GetMsgCode />
                            </div>
                          </div>
                        </el-form-item>
                      </el-form>

                      <div class="btn-box">
                        <el-button
                          type="primary"
                          @click="confirmDiscount">
                          确定
                        </el-button>
                        <el-button @click="cancelDiscount">取消</el-button>
                      </div>
                    </div>
                  </el-popover>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 订单列表 -->

        <el-tabs v-model="activeName" class="demo-tabs demo-tabs-auto-height" @tab-click="handleClick">
          <el-tab-pane label="消费账单" name="1">
          </el-tab-pane>
          <el-tab-pane label="算力券划拨记录" name="2">
          </el-tab-pane>
          <el-tab-pane label="赠送记录" name="3">
          </el-tab-pane>
          <CustomerDetailOrderList :thisMonthCost="detail.member" :tableType="activeName"/>

        </el-tabs>

      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';

import { getMemberDetail, addVoucher, changeDiscountRatio,addVoucherMoney, updateMemberRemark,getPartnerParams } from '@/api/index';

const { proxy } = getCurrentInstance();

import PageTitle from '@/components/PageTitle.vue';
import GetMsgCode from '@/components/GetMsgCode.vue';

import echarts from '@/utils/echarts.js';
import { useRoute } from 'vue-router';
const route = useRoute();
import { useUserStore } from '@/stores/user';
import { reactive, ref ,computed } from 'vue';
import CustomerDetailOrderList from './CustomerDetailOrderListForAdmin.vue';


const rules = reactive({
  rechargeMoney:[
    {required: true, message: '请输入划拨资金', trigger: 'blur'},
  ],
  voucherMoney:[
    {required: true, message: '请输入划拨划拨算力券', trigger: 'blur'},
  ],
  smsCode:[
    {required: true, message: '请输入验证码', trigger: 'blur'},
  ],
  addReason:[
    {required: true, message: '请输入赠送原因', trigger: 'blur'},
  ],
  remark:[
    {required: true, message: '请输入划拨原因', trigger: 'blur'},
  ]
})


const userStore = useUserStore();


function voucherMoneyTemp(){
  formTransfer.voucherMoney = parseFloat(formTransfer.rechargeMoney /detail.value.member.discountRatio).toFixed(2);
}

let form = reactive({
  voucherMoney: '',
  reason: '',
  smsCode: '',
  accountName: '',
  status: 1,
  
});
let formLevel = reactive({
  remark: ''
});
const codeLabel = `输入手机号为 ${userStore.user.mobile} 的验证码`;


const activeName = ref('1')
const handleClick = (tab, event) => {
  activeName.value = tab.props.name
  console.log('tab clicked:', tab.props.name,activeName.value); 
}


// 划拨
let formTransfer = reactive({
  rechargeMoney: '',
  voucherMoney: '',
  smsCode: '',
  remark:''
});




const popoverTransfer = ref(null);
const popoverIdentity = ref(null);
function confirmTransfer() {
  const { rechargeMoney, voucherMoney, smsCode,remark } = formTransfer;
  if (!rechargeMoney) {
    ElMessage.error('请输入充值金额');
    return;
  }
  if (!smsCode) {
    ElMessage.error('请输入验证码');
    return;
  }

  addVoucher({
    remark,
    smsCode,
    type: 'TRANSFER',
    userId: detail.value.member.id,
    userType:"CUSTOMER",
    voucher:parseFloat(voucherMoney),
    rechargeMoney:rechargeMoney
  }).then(res => {
    if(res.success){
      ElMessage.success('您的交易正在处理中,请耐心等待。');
    }
    popoverTransfer.value.hide();
    getMemberInfo();
  });
}

// 划转时计算伙伴的收入所需参数
const partnerParams1 = ref({
  partnerDiscountRatio: ""
});
function getPartnerParams1() {
  getPartnerParams().then(res => {
    if (res.code === 0) {
      partnerParams1.value = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
} 


function cancelIdentity() {
  popoverIdentity.value.hide();
}
function confirmRemark() {
  let { remark } = formLevel;
  updateMemberRemark({
    remark: remark,
    partnerId: Number(route.query.id)
  }).then(res => {
    ElMessage.success('修改成功');
    getMemberInfo();
    popoverIdentity.value.hide();
  });
}
function cancelTransfer() {
  popoverTransfer.value.hide();
}

// 赠送
let formSend = reactive({
  voucherMoney: '',
  addReason: '',
  smsCode: ''
});
const popoverSend = ref(null);
function searchFn() {
  console.log(111);
}
function confirmSend() {
    const { voucherMoney, addReason, smsCode } = formSend;

    if (!voucherMoney) {
      ElMessage.error('请输入赠送金额');
      return;
    }
    if (!smsCode) {
      ElMessage.error('请输入验证码');
      return;
    }

    addVoucher({
      remark:addReason,
      smsCode,
      type: 'GIVE',
      userId: detail.value.member.id,
      userType:"CUSTOMER",
      voucher:parseFloat(voucherMoney),
    }).then(res => {
      if(res.success){
        ElMessage.success('您的交易正在处理中,请耐心等待。');
      }
      popoverSend.value.hide();
      codeRest();
      getMemberInfo();
    });
  }

function cancelSend() {
  popoverSend.value.hide();
}

// 折扣调整
let formDiscount = reactive({
  discountRatio: '',
  smsCode: '',
  voucher: ''
});




const popoverDiscount = ref(null);

// 折扣对比
let showDiscountHint = ref(false);
const checkDiscount = proxy.$debounce(() => {
  if (formDiscount.discountRatio) {
    if (formDiscount.discountRatio < userStore.user.discountRatio) {
      showDiscountHint.value = true;
    } else {
      showDiscountHint.value = false;
    }
  } else {
    showDiscountHint.value = false;
  }
}, 500);

function confirmDiscount() {
  const { discountRatio, smsCode } = formDiscount;

  if (!discountRatio) {
    ElMessage.error('请输入折扣');
    return;
  }
  if (!smsCode) {
    ElMessage.error('请输入验证码');
    return;
  }

  changeDiscountRatio({
    userId: detail.value.member.id,
    discountRatio,
    smsCode,
    userType: "CUSTOMER"
  }).then(res => {
    ElMessage.success('已调整');
    popoverDiscount.value.hide();
    getMemberInfo();
  });
}

function cancelDiscount() {
  popoverDiscount.value.hide();
}

// 处理进度
function handlePercentage(month, type) {
  let res = 0;

  if (month === 1) {
    if (detail.value.lastMonthPriceTotal) {
      if (type === 1) {
        res = (detail.value.lastTakePrice / detail.value.lastMonthPriceTotal) * 100;
      } else {
        res = (detail.value.lastBackPrice / detail.value.lastMonthPriceTotal) * 100;
      }
    }
  } else {
    if (detail.value.monthPriceTotal) {
      if (type === 1) {
        res = (detail.value.takePrice / detail.value.monthPriceTotal) * 100;
      } else {
        res = (detail.value.backPrice / detail.value.monthPriceTotal) * 100;
      }
    }
  }

  return res;
}

function initLineChart() {
  let chartDom = document.getElementById('chartBox');
  if (!chartDom) {
    return;
  } else {
    echarts.dispose(chartDom);
  }

  setTimeout(() => {
    console.log(detail.value.monthList);
    let myChart = echarts.init(chartDom);
    let option = {
      tooltip: {
        trigger: 'axis'
      },
      grid: {
        top: '8%',
        left: '5%',
        right: '5%',
        bottom: '5%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: detail.value.monthList.month || []
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '预付费',
          type: 'line',
          stack: 'Total',
          data: detail.value.monthList.oneMoneyList || []
        },
        {
          name: '后付费',
          type: 'line',
          stack: 'Total',
          data: detail.value.monthList.twoMoneyList || []
        }
      ]
    };

    myChart.setOption(option, true);
  }, 300);
}

let detail = ref({});

import { getMemberDetailData } from '@/utils/mockdata';


function getMemberInfo() {
  getMemberDetail(route.query.id).then(res => {
    detail.value.member = res.data;

    nextTick(() => {
      initLineChart();
    });
  });
}



onMounted(() => {
  getMemberInfo();
  getPartnerParams1();
});
</script>

<style lang="scss" scoped>
.customer-detail-wrapper {
  .base-info {
    .info-box {
      display: flex;
      align-items: center;

      &:first-of-type {
        margin-bottom: 40px;
      }

      .item {
        min-width: 200px;
        margin-right: 20px;

        p {
          &:nth-of-type(1) {
            margin-bottom: 10px;
            color: #888;
          }

          .el-text {
            margin-left: 10px;
            cursor: pointer;
          }
        }

        .item-content {
          display: flex;
          align-items: center;

          .el-text {
            margin-left: 10px;
            cursor: pointer;
          }
        }
      }
    }
  }

  .data-info {
    .data-top-box {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .item-box {
        width: 46%;

        .amout-box {
          margin-bottom: 10px;

          p {
            &:nth-of-type(1) {
              margin-bottom: 10px;
              color: #888;
            }
          }
        }

        .process-box {
          .process-item {
            display: flex;
            align-items: center;
            margin-bottom: 10px;

            .tag-name {
              flex-shrink: 0;
              margin-right: 10px;
              color: #888;
            }

            .tag-content {
              flex: 1;
              display: flex;
              align-items: center;

              .el-progress {
                flex: 1;
                margin-right: 10px;
              }
            }
          }
        }
      }
    }

    .data-bottom-box {
      height: 200px;
    }
  }
}
.text-btn {
  text-align: left;
  margin: 0 !important;
}
.demo-tabs-auto-height {
  height: 480px;
  overflow-y: auto;
}
.popover-content{
  .title{
    font-weight: 600;
  }
  .paramsInfo{
    width: 97.5%;
    height: 60px;
    background-color: #f8e7e7;
    margin-bottom: 10px;
    .item{
      width: 33%;
      height: 100%;
      text-align: center;
      float: left;
      font-size: 12px;
      .title{
        line-height: 30px;
        font-weight: 600;
        width: 100%;
      }
      .value{
        line-height: 30px;
        width: 100%;
        margin-top: -20px;
      }
    }
  }
}
.content-item-box{
  position: relative;
  .uservoucher{
    position: absolute;
    right: 30px;
    top: -30px;
    color: #f5901c;
    line-height: 20px;
    font-size: 12px;
  }
}
</style>
